<template>
  <view 
    v-if="show"
    class="fu-toast"
    :class="[
      `fu-toast--${type}`,
      `fu-toast--${position}`
    ]"
  >
    <!-- 图标 -->

    <fu-icon color="#fff" v-if="type !== 'text'" :name="iconMap[type]"></fu-icon>
    
    <!-- 文本内容 -->
    <text class="fu-toast__text">{{ message }}</text>
  </view>
</template>

<script>
/**
 * fu-toast 轻提示组件
 * @description 轻提示组件，用于交互反馈
 * @property {Boolean} show - 是否显示
 * @property {String} type - 类型，可选值为 text success warning error loading
 * @property {String} message - 提示文本
 * @property {String} position - 位置，可选值为 top middle bottom
 * @property {Number} duration - 展示时长(ms)，值为 0 时不会自动关闭
 * @event {Function} close - 关闭时触发
 */
export default {
  name: 'fu-toast',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'text',
      validator: value => ['text', 'success', 'warning', 'error', 'loading'].includes(value)
    },
    message: {
      type: String,
      default: ''
    },
    position: {
      type: String,
      default: 'middle',
      validator: value => ['top', 'middle', 'bottom'].includes(value)
    },
    duration: {
      type: Number,
      default: 2000
    }
  },
  emits: ['update:show', 'close'],
  data() {
    return {
      timer: null,
      iconMap: {
        success: 'passed-o',
        warning: '&#xe6e6;',
        error: '&#xe6e8;',
        loading: 'loading1'
      }
    }
  },
  watch: {
    show(val) {
      if (val) {
        this.clearTimer()
        if (this.duration > 0) {
          this.timer = setTimeout(() => {
            this.onClose()
          }, this.duration)
        }
      }
    }
  },
  beforeUnmount() {
    this.clearTimer()
  },
  methods: {
    clearTimer() {
      if (this.timer) {
        clearTimeout(this.timer)
        this.timer = null
      }
    },
    onClose() {
      this.clearTimer()
      this.$emit('update:show', false)
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.fu-toast {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10000;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 32rpx;
  min-width: 200rpx;
  max-width: 70%;
  background: rgba(0, 0, 0, 0.8);
  border-radius: 16rpx;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.08);
  
  &--top {
    top: 25%;
  }
  
  &--middle {
    top: 50%;
    transform: translate(-50%, -50%);
  }
  
  &--bottom {
    bottom: 25%;
  }
  
  &__icon {
    font-family: 'fuIcon';
    font-size: 80rpx;
    color: #fff;
    margin-bottom: 20rpx;
    
    &.fu-toast--loading {
      animation: fu-rotate 0.8s linear infinite;
    }
  }
  
  &__text {
    font-size: 30rpx;
    color: #fff;
    text-align: center;
    word-break: break-all;
    line-height: 1.5;
    letter-spacing: 1rpx;
  }
}

@keyframes fu-rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 